import React, { useState, useEffect } from 'react';
import { Select, Button, Spin, Alert, Tooltip } from 'antd';
import { ReloadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { ModelInfo, LLMProvider } from '../types/index';
import { ServiceManager } from '../services/ServiceManager';

const { Option } = Select;

interface ModelSelectorProps {
  provider: LLMProvider;
  value?: string;
  onChange?: (value: string, modelInfo?: ModelInfo) => void;
  disabled?: boolean;
  placeholder?: string;
  baseURL?: string;
  apiKey?: string;
}

export const ModelSelector: React.FC<ModelSelectorProps> = ({
  provider,
  value,
  onChange,
  disabled = false,
  placeholder = "选择模型",
  baseURL,
  apiKey
}) => {
  const [models, setModels] = useState<ModelInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const serviceManager = ServiceManager.getInstance();

  // 加载模型列表
  const loadModels = async (forceRefresh = false) => {
    setLoading(true);
    setError(null);

    try {
      const config = {
        baseURL: baseURL,
        apiKey: apiKey
      };
      const modelList = await serviceManager.modelService.getModels(provider, forceRefresh, config);
      setModels(modelList);
      
      if (modelList.length === 0) {
        setError('未找到可用模型');
      }
    } catch (err) {
      console.error('加载模型列表失败:', err);
      setError(err instanceof Error ? err.message : '加载模型列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadModels();
  }, [provider, baseURL, apiKey]);

  // 刷新按钮点击处理
  const handleRefresh = () => {
    loadModels(true);
  };

  // 模型选择处理
  const handleModelChange = (modelId: string) => {
    const selectedModel = models.find(m => m.id === modelId);
    onChange?.(modelId, selectedModel);
  };

  // 渲染模型选项
  const renderModelOption = (model: ModelInfo) => (
    <Option key={model.id} value={model.id}>
      <div className="flex items-center justify-between">
        <div className="flex flex-col">
          <span className="font-medium">{model.name}</span>
          {model.description && (
            <span className="text-xs text-gray-500 truncate max-w-xs">
              {model.description}
            </span>
          )}
        </div>
        <div className="flex items-center gap-1">
          {model.contextLength && (
            <Tooltip title={`上下文长度: ${model.contextLength.toLocaleString()} tokens`}>
              <span className="text-xs bg-blue-100 text-blue-800 px-1 rounded">
                {model.contextLength >= 1000000 
                  ? `${(model.contextLength / 1000000).toFixed(1)}M`
                  : model.contextLength >= 1000 
                    ? `${Math.round(model.contextLength / 1000)}K`
                    : model.contextLength
                }
              </span>
            </Tooltip>
          )}
          {model.capabilities && model.capabilities.includes('vision') && (
            <Tooltip title="支持视觉能力">
              <span className="text-xs bg-green-100 text-green-800 px-1 rounded">
                👁️
              </span>
            </Tooltip>
          )}
          {model.capabilities && model.capabilities.includes('coding') && (
            <Tooltip title="编程专用">
              <span className="text-xs bg-purple-100 text-purple-800 px-1 rounded">
                💻
              </span>
            </Tooltip>
          )}
        </div>
      </div>
    </Option>
  );

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <Select
          className="flex-1"
          value={value}
          onChange={handleModelChange}
          placeholder={placeholder}
          disabled={disabled || loading}
          loading={loading}
          showSearch
          filterOption={(input, option) => {
            const model = models.find(m => m.id === option?.value);
            if (!model) return false;
            
            const searchText = input.toLowerCase();
            return (
              model.name.toLowerCase().includes(searchText) ||
              model.id.toLowerCase().includes(searchText) ||
              (model.description && model.description.toLowerCase().includes(searchText))
            );
          }}
          dropdownRender={(menu) => (
            <div>
              {menu}
              {models.length > 0 && (
                <div className="border-t p-2 text-xs text-gray-500">
                  共 {models.length} 个模型
                </div>
              )}
            </div>
          )}
        >
          {models.map(renderModelOption)}
        </Select>
        
        <Tooltip title="刷新模型列表">
          <Button
            icon={<ReloadOutlined />}
            onClick={handleRefresh}
            loading={loading}
            disabled={disabled}
            type="default"
          />
        </Tooltip>
      </div>

      {error && (
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
          action={
            <Button size="small" onClick={() => loadModels()}>
              重试
            </Button>
          }
        />
      )}

      {!loading && models.length === 0 && !error && (
        <Alert
          message="暂无可用模型"
          description="请检查网络连接或稍后重试"
          type="info"
          showIcon
        />
      )}

      {value && models.length > 0 && (
        <div className="text-xs text-gray-600">
          {(() => {
            const selectedModel = models.find(m => m.id === value);
            if (!selectedModel) return null;
            
            return (
              <div className="flex items-center gap-2">
                <InfoCircleOutlined />
                <span>
                  {selectedModel.contextLength && 
                    `上下文: ${selectedModel.contextLength.toLocaleString()} tokens`
                  }
                  {selectedModel.capabilities && selectedModel.capabilities.length > 0 && (
                    <span className="ml-2">
                      能力: {selectedModel.capabilities.join(', ')}
                    </span>
                  )}
                </span>
              </div>
            );
          })()}
        </div>
      )}
    </div>
  );
};